package com.yzf.enterprise.framework.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yzf.enterprise.common.enums.UserStatus;
import com.yzf.enterprise.common.exception.BaseException;
import com.yzf.enterprise.entity.User;
import com.yzf.enterprise.framework.security.LoginUser;
import com.yzf.enterprise.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class MyUserDetailsService implements UserDetailsService {

	Logger logger = LoggerFactory.getLogger(MyUserDetailsService.class);

	@Autowired
	private UserMapper userMapper;

	@Override
	public UserDetails loadUserByUsername(String userKey) throws UsernameNotFoundException {
		//通过用户名查询用户信息
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_key",userKey);
        User user=userMapper.selectOne(queryWrapper);
        if (null == user) {
            logger.info("登录用户：{} 不存在.", userKey);
            throw new UsernameNotFoundException("登录用户：" + userKey + " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(user.getStatus().toString())) {
            logger.info("登录用户：{} 已被删除.", userKey);
            throw new BaseException("对不起，您的账号：" + userKey + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus().toString())) {
            logger.info("登录用户：{} 已被停用.", userKey);
            throw new BaseException("对不起，您的账号：" + userKey + " 已停用");
        }
        return new LoginUser(user);
	}


}